package com.mall.user.mq.producer;

import com.alibaba.fastjson.JSON;
import com.mall.user.dto.UserRegisterRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class SendMailProducer {

    private DefaultMQProducer producer;

    @PostConstruct
    public void init(){
        producer = new DefaultMQProducer("verifyMail-producer");
        producer.setNamesrvAddr("127.0.0.1:9876");
        try {
            producer.start();
        } catch (MQClientException e) {
            e.printStackTrace();
        }
    }

    public void sendMail(String uuid, UserRegisterRequest request) {
        Map<String, String> map = new HashMap<>();
        map.put("topic","Never Debug 会员用户激活");
        map.put("text","http://localhost:8080/user/verify?uuid=" + uuid + "&userName=" + request.getUserName());
        map.put("from","irajames4j@163.com");
        map.put("to",request.getEmail());
        Message message = new
                Message("verifyMail","message", JSON.toJSONString(map).getBytes());
        SendResult sendResult=null;
        try {
            sendResult = producer.send(message);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (sendResult != null && SendStatus.SEND_OK.equals(sendResult.getSendStatus())) {
            log.info("注册激活消息发送成功： " + sendResult.getMsgId());
            return;
        }
        log.info("注册激活消息发送失败");
    }
}
